<template>
  <el-card>
    <el-form inline>
      <el-form-item label="一级分类">
        <!-- 
          1.下拉列表要选中内容，记得select给v-model收集表单数据
          2.option中，:label="显示内容" :value="要收集的数据"
         -->
        <el-select placeholder="请选择" v-model="category.category1Id">
          <el-option
            :label="c1.name"
            :value="c1.id"
            v-for="c1 in category.category1List"
            :key="c1.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select placeholder="请选择" v-model="category.category2Id">
          <el-option
            :label="c2.name"
            :value="c2.id"
            v-for="c2 in category.category2List"
            :key="c2.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select placeholder="请选择" v-model="category.category3Id">
          <el-option
            :label="c3.name"
            :value="c3.id"
            v-for="c3 in category.category3List"
            :key="c3.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "CategorySelector",
};
</script>

<script lang="ts" setup>
import { onMounted, reactive, watch } from "vue";
import {
  getCategory1ListApi,
  getCategory2ListApi,
  getCategory3ListApi,
} from "@/api/product/category";
import type { Category } from "@/api/product/model/categoryModel";
const category = reactive<Category>({
  category1List: [],
  category2List: [],
  category3List: [],
  category1Id: undefined,
  category2Id: undefined,
  category3Id: undefined,
});
// 获取一级分类数据
onMounted(async () => {
  category.category1List = await getCategory1ListApi();
});
// 获取二级分类数据
watch(
  () => category.category1Id,
  async (category1Id) => {
    // 清空二级表单有的数据
    category.category2Id = undefined;
    category.category3Id = undefined;

    // 监视一级分类的Id改变就获取对应的二级分类列表
    category.category2List = await getCategory2ListApi(category1Id as number);
    category.category3List = [];
  }
);
// 获取三级分类数据
watch(
  () => category.category2Id,
  async (category2Id) => {
    if (!category.category2Id) return;
    category.category3Id = undefined;
    // 监视二级分类的Id改变就获取对应的三级分类列表
    category.category3List = await getCategory3ListApi(category2Id as number);
  }
);
</script>

<style scoped>
/* 父组件修改子组件用deep深度样式，直接写.el-form-item 是因为它是子组件的根标签 */
/* .el-form-item{
  margin-top: 10px;
  margin-bottom: 10px;
} */
:deep(.el-form-item) {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
